package com.onemile.app;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.json.JSONArray;
import org.json.JSONObject;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.telephony.gsm.GsmCellLocation;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.CoordinateConvert;
import com.baidu.mapapi.GeoPoint;
import com.baidu.mapapi.ItemizedOverlay;
import com.baidu.mapapi.LocationListener;
import com.baidu.mapapi.MKAddrInfo;
import com.baidu.mapapi.MKDrivingRouteResult;
import com.baidu.mapapi.MKGeneralListener;
import com.baidu.mapapi.MKLocationManager;
import com.baidu.mapapi.MKPlanNode;
import com.baidu.mapapi.MKPoiResult;
import com.baidu.mapapi.MKSearch;
import com.baidu.mapapi.MKSearchListener;
import com.baidu.mapapi.MKTransitRouteResult;
import com.baidu.mapapi.MKWalkingRouteResult;
import com.baidu.mapapi.MapActivity;
import com.baidu.mapapi.MapController;
import com.baidu.mapapi.MapView;
import com.baidu.mapapi.MyLocationOverlay;
import com.baidu.mapapi.Overlay;
import com.baidu.mapapi.OverlayItem;
import com.baidu.mapapi.PoiOverlay;
import com.baidu.mapapi.RouteOverlay;
import com.baidu.mapapi.TransitOverlay;
import com.onemile.app.OneMileActivity.loader;
import com.onemile.utils.UtiDialogsFactory;

public class UIbaidu extends MapActivity
{

   MapView mMapView;
   MapController mMapController;
   BMapManager mBMapMan;
   MKSearch mMkSearch;

   private int CONNECTION_TIMEOUT = 20000;
   private int SO_TIMEOUT = 20000;

   float lat;
   float lon;

   @Override
   protected void onCreate(Bundle saveInstanceBundle)
   {
	  super.onCreate(saveInstanceBundle);
	  setContentView(R.layout.baidu);

	  Button btn1 = (Button) findViewById(R.id.btn1);
	  Button btn2 = (Button) findViewById(R.id.btn2);
	  Button btn3 = (Button) findViewById(R.id.btn3);
	  Button btn4 = (Button) findViewById(R.id.btn4);
	  btn1.setOnClickListener(new OnClickListener()
	  {
		 @Override
		 public void onClick(View v)
		 {
			mMapView.setSatellite(true);
		 }
	  });

	  btn2.setOnClickListener(new OnClickListener()
	  {
		 @Override
		 public void onClick(View v)
		 {
			// TODO Auto-generated method stub
			mMapView.setSatellite(false);
		 }
	  });

	  btn3.setOnClickListener(new OnClickListener()
	  {
		 @Override
		 public void onClick(View v)
		 {
			// TODO Auto-generated method stub
			try
			{

			   UtiDialogsFactory.getInstance().ShowLoadingDialogNoTitle(UIbaidu.this, "loading");
			   loader l = new loader();
			   l.execute("");

			}
			catch (Exception e)
			{
			   e.printStackTrace();
			}

		 }
	  });
	  
	  btn4.setOnClickListener(new OnClickListener()
	  {
		 @Override
		 public void onClick(View v)
		 {
			MyLocationOverlay locationOverlay=new MyLocationOverlay(UIbaidu.this, mMapView);
			locationOverlay.enableMyLocation();
			locationOverlay.enableCompass();
			mMapView.getOverlays().add(locationOverlay);
			
		    mMapController.setCenter(locationOverlay.getMyLocation()); // 设置地图中心点
		    mMapController.setZoom(18); // 设置地图zoom级别
//			 GeoPoint point =locationOverlay.getMyLocation();
//			 mMapView.setSatellite(true);
//			 mMapController.setCenter(point); // 设置地图中心点
//			 mMapController.setZoom(12); // 设置地图zoom级别
		 }
	  });
//	  
	  mBMapMan = new BMapManager(getApplication());
	  mBMapMan.init("4DCA0D0A4075774691418AD4DDBA00AB33691B13", null);
	  super.initMapActivity(mBMapMan);

	  mMkSearch=new MKSearch();
//	  mMkSearch.reverseGeocode(new GeoPoint(arg0, arg1));
	  
	  mMapView = (MapView) findViewById(R.id.bmapsView);
	  mMapView.setBuiltInZoomControls(true); // 设置启用内置的缩放控件

	  mMapController = mMapView.getController(); // 得到mMapView的控制权,可以用它控制和驱动平移和缩放
	  mMapView.setSatellite(true);
   }
   
//   @Override         
//   public void onGetAddrResult(MKAddrInfo res, int error)  
//   {              
//
//   }

   @Override
   protected boolean isRouteDisplayed()
   {

	  return false;
   }

   @Override
   protected void onDestroy()
   {
	  if (mBMapMan != null)
	  {
		 mBMapMan.destroy();
		 mBMapMan = null;
	  }
	  super.onDestroy();
   }

   @Override
   protected void onPause()
   {
	  if (mBMapMan != null)
	  {
		 mBMapMan.stop();
	  }
	  super.onPause();
   }

   @Override
   protected void onResume()
   {
	  if (mBMapMan != null)
	  {
		 mBMapMan.start();
	  }
	  super.onResume();
   }

   class loader extends AsyncTask<String, Integer, String>
   {

	  @Override
	  protected String doInBackground(String... params)
	  {
		 TelephonyManager tm = (TelephonyManager) UIbaidu.this.getSystemService(Context.TELEPHONY_SERVICE);
		 try
		 {
			GsmCellLocation gcl = (GsmCellLocation) tm.getCellLocation();
			int cid = gcl.getCid();
			int lac = gcl.getLac();
			int mcc = Integer.valueOf(tm.getNetworkOperator().substring(0, 3));
			int mnc = Integer.valueOf(tm.getNetworkOperator().substring(3, 5));
			String IMEI = tm.getDeviceId();

			// ��װJSON��ѯ�ַ�
			JSONObject holder = new JSONObject();
			holder.put("version", "1.1.0");
			holder.put("host", "maps.google.com");
			// holder.put("address_language", "zh_CN");
			holder.put("request_address", true);

			JSONArray array = new JSONArray();
			JSONObject data = new JSONObject();
			data.put("cell_id", cid); // 25070
			data.put("location_area_code", lac);// 4474
			data.put("mobile_country_code", mcc);// 460
			data.put("mobile_network_code", mnc);// 0
			array.put(data);
			holder.put("cell_towers", array);

			// �������ӣ��������󲢽��ܻ�Ӧ
			DefaultHttpClient client = new DefaultHttpClient();

			client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, CONNECTION_TIMEOUT);
			client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, SO_TIMEOUT);

			HttpPost post = new HttpPost("http://www.google.com/loc/json");

			StringEntity se = new StringEntity(holder.toString());

			post.setEntity(se);
			HttpResponse resp = client.execute(post);

			HttpEntity entity = resp.getEntity();

			BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent()));
			StringBuffer sb = new StringBuffer();
			String result = br.readLine();

			while (result != null)
			{
			   sb.append(result);
			   result = br.readLine();
			}
			JSONObject jsonObject = new JSONObject(sb.toString());

			JSONObject jsonObject1 = new JSONObject(jsonObject.getString("location"));

			lat = Float.valueOf(jsonObject1.getString("latitude"));
			lon = Float.valueOf(jsonObject1.getString("longitude"));
		 }
		 catch (Exception e)
		 {
			// TODO: handle exception
			e.printStackTrace();
		 }
		 return null;
	  }

	  @Override
	  protected void onPostExecute(String result)
	  {
		 UtiDialogsFactory.getInstance().DismissLoadingDialog();

		 GeoPoint point = new GeoPoint((int) (lat * 1000000), (int) (lon * 1000000)); // 用给定的经纬度构造一个GeoPoint，单位是微度
		 GeoPoint p2 = CoordinateConvert.bundleDecode(CoordinateConvert.fromWgs84ToBaidu(point));

		 
		 mMapController.setCenter(point); // 设置地图中心点
		 mMapController.setZoom(18); // 设置地图zoom级别
		 

	  }

   }

}
